#!/usr/bin/env node
'use strict';

/*
 * This script normalizes all the specs in examples/specs and
 * writes the full normalized spec to `examples/specs/normalized`
 * the normalized spec is different than the original.
 * We output this to a different folder so that build-examples script does not generate
 * redundant Vega output specs.
 */

const fs = require('fs');
const vl = require('../build/vega-lite');
const stableStringify = require('fast-json-stable-stringify');
const compactStringify = require('json-stringify-pretty-compact');

const DIR = __dirname + '/..';
const SPECS = '/examples/specs';
const examples = fs.readdirSync(DIR + SPECS);

examples.forEach(example => {
  if (example && example.includes('.vl.json')) {
    const path = DIR + SPECS + '/' + example;
    const spec = JSON.parse(fs.readFileSync(path));

    const preNormalized = stableStringify(spec);
    const fullSpec = vl.normalize(spec);
    const postNormalized = stableStringify(fullSpec);

    // console.log(preNormalized, postNormalized);
    if (preNormalized !== postNormalized) {
      const postNormalizedOutput = compactStringify(fullSpec, null, 2);
      // -8 is cutting .vl.json
      const newFilename = example.slice(0, -8) + '_normalized.vl.json';
      const newFilenameAndPath = DIR + SPECS + '/normalized/' + newFilename;
      fs.writeFile(newFilenameAndPath, postNormalizedOutput, err => {
        if (err) return console.log(err);
        console.log('Built:', newFilename);
      });
    }
  }
});
